<?php

namespace frontend\controllers;
use common\models\ShoppingCart;
use yii;
use yii\data\Pagination;
use common\models\SmsWeb;
use common\models\Post;
use common\models\Order;
use common\models\Fund;
use common\models\Product;
use common\components\Myhelpers;
use common\models\User;
class MycountController extends FController
{
    public function init(){
        parent::init();
        if(Yii::$app->user->isGuest){
            $this->redirect('/site/login');
            Yii::$app->end();
        }
    }
    public $enableCsrfValidation = false;
    public $layout = 'left.php';

    //我的账户中心
    public function actionCenter(){
    
        $uid = Yii::$app->user->id;

        //订单状态统计
        for ($i=1; $i <6 ; $i++) { 
            $num = (new \Yii\db\Query())
                    ->select('count(id)')
                    ->from('order')
                    ->where(['user_id'=>$uid,'order_status'=>$i])
                    ->scalar();
            $count[$i]['num'] = $num;
            $count[$i]['name'] = Order::itemAlias('order_status',$i);                    
        }
        //查询用户信息
        $user_info = User::find()
                    ->select('*')
                    ->where('id = :id',[':id'=>$uid])
                    ->asArray()
                    ->one();
        //用户收藏的商品                    
        $collection = (new \yii\db\Query())
                    ->select('a.id cid,b.*')
                    ->from('collection a')
                    ->where(['a.user_id' => $uid])
                    ->leftJoin(['b'=>'product'],'b.id = a.product_id')
                    ->groupBy('b.id')
                    ->all();

        //显示最近浏览记录
        $recently_pid = Yii::$app->request->cookies->getvalue('recently_pid');
        $scan_list = [];
        if($recently_pid){
            //分配浏览记录到页面
            foreach ($recently_pid as $k => $v) {
                $scan_list[$k] = Product::find()
                      ->select('id,name,product_price,price_unit,spec,img_url')
                      ->where(['id'=>$v])
                      ->asArray()
                      ->one();
                      //var_dump($scan_list);
                }
        }
        
    	return $this->render('center',[
            'user_info' => $user_info,
            'collection' => $collection,
            'scan_list' => $scan_list,
            'count' => $count,
        ]);
    }

    /**
     * @desc 我的进货单（购物车列表）
     */
    public function actionCartList(){
        $this->layout='main.php';
        $db = Yii::$app->db;
        $user_id = Yii::$app->user->id;

        //我的购物车数据
        $rs['carts'] = (new \Yii\db\Query())
                    ->select('a.*,b.price_unit')
                    ->from('shopping_cart AS a')
                    ->where('user_id=:user_id', [':user_id'=>$user_id])
                    ->leftJoin('product b','b.id = a.product_id')
                    ->orderBy('id DESC')
                    ->all();
        //总数量
        $sql = "SELECT SUM(`product_price`*`product_num`) `total_price`, SUM(`product_num`) `total_num`, COUNT(*) `count_carts`  FROM `shopping_cart` WHERE `user_id`={$user_id}";
        $rs['total'] = $db->createCommand($sql)->queryOne();

        return $this->render('cart_list', $rs);
    }

    //资金
    public function actionMoney(){
        $uid = Yii::$app->user->id;

        $fund = Fund::find()
                ->where('user_id=:uid', [':uid'=>$uid])
                ->orderBy('id DESC');
       //框架自带的跳转分页
        $pages = new Pagination(
            [
                'totalCount' => $fund->count(),
                /*'pageSize'=>'3',*/
                'defaultPageSize' => 10,        //------自行设置每页显示的资金明细记录
                'validatePage' => false,
            ]
        );

        $fund_sum = $fund->count();
        $page_sum = intval(($fund->count()+$pages->limit-1)/$pages->limit);

        $fund_record = $fund->limit($pages->limit)->offset($pages->offset)->all();

    	return $this->render('money',[
            'pages' => $pages,
            'fund_record' => $fund_record
        ]);
    }

    //消息列表
    public function actionMessage(){
        $qb = Myhelpers::RemoveXSS(Yii::$app->request->post('qb'));
        $lid = Myhelpers::RemoveXSS(Yii::$app->request->post('name'));
        $id = Yii::$app->user->id;
        if($lid){
       Yii::$app->db->createCommand()->update('sms_web', ['is_read' => 2,'is_delete'=>1,'user_id'=>$id], "id='{$lid}'")->execute();
           return $lid;
        }
        if($qb){
            Yii::$app->db->createCommand()->update('sms_web', ['is_read' => 2,'is_delete'=>1,'user_id'=>$id])->execute();
           return '1';
        }
        $query = SmsWeb::find()
            ->where(['is_delete'=>1,'user_id'=>$id] )
            ->orderBy('id DESC');
        $countQuery = clone $query;
        $pages = new Pagination(['totalCount' => $countQuery->count(),'pageSize'=>'6','defaultPageSize' => 10]);
        $models = $query->offset($pages->offset)
            ->limit($pages->limit)
            ->orderBy('is_read asc')
            ->all();
        Yii::$app->view->params['page']['page_title'] = '消息中心 - ' . $this->w_config['website_name'];
         return $this->render('message',[
            'models' => $models,
            'pages' => $pages,
            //'m' => $m,
         ]);
      
    }

    //详细详情
   public function actionDetail($id)
    {   
        $uid = Yii::$app->user->id;
        $id=intval($id);
        $model=SmsWeb::find()
        ->where(['is_delete'=>1,'user_id'=>$uid,'id'=>$id])
        ->one();
       return $this->render('detail', [
            'model'=>$model,
        ]);
    }
    //删除消息
     public function actionDelete(){
        $user_id = Yii::$app->user->id;
        $db = Yii::$app->db;
        do{
            $id = htmlspecialchars(Yii::$app->request->post('id'));
            $id = trim($id, ',');
            if( !$id ) {
                $rs = array('errNo' => 1, 'msg' => '参数有误');
            }else {
                $sql = "UPDATE `sms_web` SET is_delete=2,is_read=2 WHERE `user_id`={$user_id} AND `id` IN($id)";
                $result = $db->createCommand($sql)->execute();
                if( !$result ) {
                    $rs = array('errNo' => 2, 'msg' => '删除失败');
                }else{
                    $rs = array('errNo' => 3, 'msg' => '删除成功');
                }
            }
        }while(false);

        exit(json_encode($rs));
    }
}
